/*
 * Copyright 2007-2008 by Matthias Buch-Kromann <mbk.isv@cbs.dk>.
 * 
 * This file is part of the Open-source Dependency Toolkit (OSDT),
 * see http://code.google.com/p/open-source-dependency-toolkit. 
 * 
 * The OSDT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * The OSDT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the OSDT in the files COPYING and COPYING.LESSER. If
 * not, see http://www.gnu.org/licenses.
 */

package org.osdtsystem.functions;

import org.osdtsystem.exceptions.FunctionVariableException;
import org.osdtsystem.graphs.GraphAccessor;

/**
 * A function that sets/gets a variable during the evaluation of the function.
 * @param <V> 
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
public class FuncVariable<V> extends AbstractSingletonFunction<V> {
    String name;
    static int id = 0;
    
    FuncVariable(Class<V> classname) {
        this(classname, "_" + String.valueOf(++id));
    }
    
    FuncVariable(Class<V> classname, String name) {
        super();
        this.name = name;
        addLocalFreeVariable(name);
    }

    @Override
    public V _singletonFunctionValue(LocalFunction<?, ?> caller,
            FunctionContext context, GraphAccessor accessor) {
        V var = (context == null || name == null) ? null : (V) context.variable(name);
        if (var != null) {
            return var;
        } else {
            throw new FunctionVariableException("Variable " + name + " not defined in function context");
        }
    }

    @Override
    void toStringBuilder(FunctionStringBuilder builder) {
        builder.addParameter("name", name);
    }
}
